﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml.Linq;
using System.Xml;
using System.IO;

namespace VatanComputerBot
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private bool DeleteFile(string path)
        {
            try
            {
                File.Delete(@path);
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Style = ProgressBarStyle.Marquee;
            backgroundWorker1.RunWorkerAsync();
        }

        private void button2_Click(object sender, EventArgs e)
        {

            backgroundWorker2.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
            {
                client.DownloadFile(@"http://www.vatanbilgisayar.com/category.aspx?id=1", @"page.html");
            }
            List<Category> list = Bot.BotBase.GetCategoryList(@"page.html", "//div[@class='divSecenekCategory']/a");
            File.Delete(@"page.html");
            XElement root = new XElement("Categories");
            XElement tmp = null;
            foreach (Category c in list)
            {
                tmp = new XElement("Category");
                tmp.SetAttributeValue("name", c.name);
                tmp.SetAttributeValue("link", c.link);
                root.Add(tmp);
            }
            try
            {
                root.Save("CategoryList.xml");
            }
            catch
            {
                MessageBox.Show("Dosya yazma hatası oluştu", "Hata");
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 100;
            progressBar1.Style = ProgressBarStyle.Blocks;
        }
        private bool downloadFile(string source, string destination)
        {
            using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
            {
                try
                {
                    client.Encoding = Encoding.Unicode;
                    client.DownloadFile(@source, @destination);
                    client.Dispose();
                    return true;
                }
                catch
                {
                    client.Dispose();
                    return false;
                }
            }
        }
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            XElement Categories = XElement.Load("CategoryList.xml");
            XElement root = new XElement("Products");
            XElement tmp = null;
            const int inc = 20;
            for (int i = 0; i < Categories.Elements().ToList().Count; i++)
            {
                XElement category = Categories.Elements().ElementAt(i);
                while (!downloadFile("http://www.vatanbilgisayar.com/" + @category.Attributes().ElementAt(1).Value, @"page2.html"))
                    ;
                int count = Bot.BotBase.GetProductCount(@"page2.html", "//span[@id='ctl00_ContentPlaceHolder1_lblRecordCount']");
                while (!DeleteFile(@"page2.html")) ;
                for (int start = 1; start < count; start += inc)
                {
                    category = Categories.Elements().ElementAt(i);
                    while (!downloadFile("http://www.vatanbilgisayar.com/" + @category.Attributes().ElementAt(1).Value + "&rcd=" + start, @"page1.html"))
                        ;
                    List<ProductInfo> list = Bot.BotBase.GetProductList(@"page1.html", "//div[@id='dgDetail']/table//tr[3]/td/div");
                    while (!DeleteFile(@"page1.html")) ;
                    if (list == null)
                    {
                        continue;
                    }
                    tmp = null;
                    foreach (ProductInfo p in list)
                    {
                        tmp = new XElement("ProductInfo");
                        tmp.SetAttributeValue("type", category.Attributes().ElementAt(0).Value);
                        tmp.SetAttributeValue("productName", p.productName);
                        tmp.SetAttributeValue("productLink", p.link);
                        tmp.SetAttributeValue("brandName", p.brandName);
                        root.Add(tmp);
                    }
                }
                backgroundWorker2.ReportProgress((i + 1) * 100 / Categories.Elements().ToList().Count);
            }
            try
            {
                root.Save("ProductInfoList.xml");
                MessageBox.Show("ProductInfoList.xml oluşturuldu", "Bilgi");
            }
            catch
            {
                MessageBox.Show("Dosya yazma hatası oluştu", "Hata");
            }

        }

        private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar2.Value = e.ProgressPercentage;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            backgroundWorker3.RunWorkerAsync();
            MessageBox.Show("İşlem Başlatıldı.", "Mesaj");
        }
        private int notNegative(int number)
        {
            if (number < 0)
                return 0;
            return number;
        }

        private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
        {
            XElement Products = XElement.Load("ProductInfoList.xml");
            XElement root = new XElement("Mainboards");
            List<XElement> mainBoardList = (from node in Products.Elements().ToList()
                                            where node.Attribute("type").Value == "Anakartlar"
                                            select node).ToList();

            XElement tmp = null;
            string content = null;
            string xpath = null;
            int i = 0;
            foreach (XElement mb in mainBoardList)
            {
                tmp = new XElement("Mainboard");
                const string page = @"page2.html";
                const string baseTable = "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik_rptProps']" + "/tr/td";
                while (!downloadFile("http://www.vatanbilgisayar.com" + mb.Attribute("productLink").Value, page)) ;
                tmp.Add(mb);
                xpath = Bot.BotBase.GetXPathOfInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik']" + "/table/tr/td", "Ürün Kodu").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("model", content.Split('&').First());

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "İşlemci Teknolojisi").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("processorTech", content);

                content = Bot.BotBase.GetInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_tcnOdeme_tplVCard_dgOdemeVCard_ctl04_lblPrcTL']");
                if (content != null)
                    tmp.SetAttributeValue("cost", content.Split().First());

                content = Bot.BotBase.GetAttribute(page, "//*[@id='ctl00_ContentPlaceHolder1_imgBig']", "src");
                if (content != null)
                    tmp.SetAttributeValue("imgUrl", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Yapı").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("structure", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "İşlemci Soket Tipi").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("socketType", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hafıza (RAM) Tipi").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("ramType", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "MB Ram Slot sayısı").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("ramSlotCount", content);
                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "MB Chipseti").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("chipset", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hafıza Bus Hızı").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("busSpeed", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "HD I/O").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("hdio", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "ONBOARD").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("onboard", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "MB PCI Express").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("pciExpress", content);

                root.Add(tmp);
                while (!DeleteFile(@"page2.html")) ;
                i++;
                backgroundWorker3.ReportProgress(i * 100 / mainBoardList.Count);
            }
            root.Save("MainboardList.xml");
        }

        private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker3_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("İşlem Tamamlandı.", "Mesaj");
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            backgroundWorker4.RunWorkerAsync();
            MessageBox.Show("İşlem Başlatıldı.", "Mesaj");
        }

        private void backgroundWorker4_DoWork(object sender, DoWorkEventArgs e)
        {
            XElement Products = XElement.Load("ProductInfoList.xml");
            XElement root = new XElement("RAMs");
            List<XElement> ramList = (from node in Products.Elements().ToList()
                                      where node.Attribute("type").Value == "Hafıza Ürünleri (RAM)"
                                      select node).ToList();

            XElement tmp = null;
            string content = null;
            string xpath = null;
            int i = 0;
            foreach (XElement mb in ramList)
            {
                tmp = new XElement("RAM");
                const string page = @"page2.html";
                const string baseTable = "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik_rptProps']" + "/tr/td";
                while (!downloadFile("http://www.vatanbilgisayar.com" + mb.Attribute("productLink").Value, page)) ;
                tmp.Add(mb);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik']" + "/table/tr/td", "Ürün Kodu").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("model", content.Split('&').First());

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "KULLANIM").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("usage", content);

                content = Bot.BotBase.GetInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_tcnOdeme_tplVCard_dgOdemeVCard_ctl04_lblPrcTL']");
                if (content != null)
                    tmp.SetAttributeValue("cost", content.Split().First());

                content = Bot.BotBase.GetAttribute(page, "//*[@id='ctl00_ContentPlaceHolder1_imgBig']", "src");
                if (content != null)
                    tmp.SetAttributeValue("imgUrl", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hafıza (RAM) Kapasitesi").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("capacity", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hafıza (RAM) Tipi").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("ramType", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hafıza Bus Hızı").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("busSpeed", content);

                root.Add(tmp);
                while (!DeleteFile(@"page2.html")) ;
                i++;
                backgroundWorker4.ReportProgress(i * 100 / ramList.Count);
            }
            root.Save("RAMList.xml");
        }

        private void backgroundWorker4_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar2.Value = e.ProgressPercentage;
        }

        private void backgroundWorker4_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            MessageBox.Show("İşlem Tamamlandı.", "Mesaj");
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            backgroundWorker5.RunWorkerAsync();
            MessageBox.Show("İşlem Başlatıldı.", "Mesaj");
        }

        private void backgroundWorker5_DoWork(object sender, DoWorkEventArgs e)
        {
            XElement Products = XElement.Load("ProductInfoList.xml");
            XElement root = new XElement("Cases");
            List<XElement> caseList = (from node in Products.Elements().ToList()
                                       where node.Attribute("type").Value == "Bilgisayar Kasası"
                                       select node).ToList();

            XElement tmp = null;
            string content = null;
            string xpath = null;
            int i = 0;
            foreach (XElement mb in caseList)
            {
                tmp = new XElement("Case");
                const string page = @"page2.html";
                const string baseTable = "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik_rptProps']" + "/tr/td";
                while (!downloadFile("http://www.vatanbilgisayar.com" + mb.Attribute("productLink").Value, page)) ;
                tmp.Add(mb);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik']" + "/table/tr/td", "Ürün Kodu").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("model", content.Split('&').First());

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Kasa Boyutu").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("size", content);

                content = Bot.BotBase.GetInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_tcnOdeme_tplVCard_dgOdemeVCard_ctl04_lblPrcTL']");
                if (content != null)
                    tmp.SetAttributeValue("cost", content.Split().First());

                content = Bot.BotBase.GetAttribute(page, "//*[@id='ctl00_ContentPlaceHolder1_imgBig']", "src");
                if (content != null)
                    tmp.SetAttributeValue("imgUrl", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Yapı").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("structure", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "G&#252;&#231; Kaynağı (W)").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("powerSupply", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "&#199;ıkışlar").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("outputs", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Fan").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("fan", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Renk").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("color", content);

                root.Add(tmp);
                while (!DeleteFile(@"page2.html")) ;
                i++;
                backgroundWorker5.ReportProgress(i * 100 / caseList.Count);
            }
            root.Save("CaseList.xml");
        }

        private void backgroundWorker5_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar3.Value = e.ProgressPercentage;
        }

        private void backgroundWorker5_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("İşlem Tamamlandı.", "Mesaj");
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            backgroundWorker6.RunWorkerAsync();
            MessageBox.Show("İşlem Başlatıldı.", "Mesaj");
        }

        private void backgroundWorker6_DoWork(object sender, DoWorkEventArgs e)
        {
            XElement Products = XElement.Load("ProductInfoList.xml");
            XElement root = new XElement("Speakers");
            List<XElement> speakerList = (from node in Products.Elements().ToList()
                                          where node.Attribute("type").Value == "Hoparlör"
                                          select node).ToList();

            XElement tmp = null;
            string content = null;
            string xpath = null;
            int i = 0;
            foreach (XElement mb in speakerList)
            {
                tmp = new XElement("Speaker");
                const string page = @"page2.html";
                const string baseTable = "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik_rptProps']" + "/tr/td";
                while (!downloadFile("http://www.vatanbilgisayar.com" + mb.Attribute("productLink").Value, page)) ;
                tmp.Add(mb);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_TabContainer2_tabOzellik']" + "/table/tr/td", "Ürün Kodu").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("model", content.Split('&').First());

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hoparlör Sistemi").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("soundSystem", content);

                content = Bot.BotBase.GetInnerText(page, "//*[@id='ctl00_ContentPlaceHolder1_tcnOdeme_tplVCard_dgOdemeVCard_ctl04_lblPrcTL']");
                if (content != null)
                    tmp.SetAttributeValue("cost", content.Split().First());

                content = Bot.BotBase.GetAttribute(page, "//*[@id='ctl00_ContentPlaceHolder1_imgBig']", "src");
                if (content != null)
                    tmp.SetAttributeValue("imgUrl", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Hoparlör Gücü").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("speakerPower", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Subwoofer Çıkış Gücü").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("subwooferOutputPower", content);

                xpath = Bot.BotBase.GetXPathOfInnerText(page, baseTable, "Uydu Hoparlör Çıkış Gücü").Trim();
                xpath = xpath.Substring(0, notNegative(xpath.Length - 3));
                content = Bot.BotBase.GetInnerText(page, xpath + "[2]");
                if (content != null)
                    tmp.SetAttributeValue("sataliteOutputPower", content);

                root.Add(tmp);
                while (!DeleteFile(@"page2.html")) ;
                i++;
                backgroundWorker6.ReportProgress(i * 100 / speakerList.Count);
            }
            root.Save("SpeakerList.xml");
        }

        private void backgroundWorker6_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar4.Value = e.ProgressPercentage;
        }

        private void backgroundWorker6_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("İşlem Tamamlandı.", "Mesaj");
        }

    }
}
